<?php
namespace app\admin\controller;

use app\common\model\KwReply as KwReplyModel;
use app\common\controller\AdminBase;

class KwReply extends AdminBase
{
    protected $kw_reply_model;

    public function _initialize(){
        parent::_initialize();
        $this->kw_reply_model = new KwReplyModel;
    }

    public function index(){
        $kw_reply_list = $this->kw_reply_model->showList();
        $this->assign('kw_reply_list',$kw_reply_list);
        return $this->fetch();
    }

    public function add(){
        return $this->fetch();
    }

    public function save(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $save_data = [
                'name' => $data['name'],
                'mode' => $data['mode'],
            ];

            foreach($data['match'] as $k=>$v){
                $save_data['keyword_list_info'][] = [
                    'match_mode' => $v,
                    'content' => $data['keyword'][$k],
                ];
            }

            foreach($data['type'] as $k2=>$v2){
                $save_data['reply_list_info'][] = [
                    'type' => $v2,
                    'content' => $data['content'][$k2],
                ];
            }

            $result = $this->kw_reply_model->allowField(true)->save($save_data);
            if($result){
                return $this->success('保存成功','admin/kw_reply/index');
            }else{
                return $this->success('保存失败');
            }
        }
    }

    public function edit($id){
        $kw_reply_info = $this->kw_reply_model->showOne($id);
        $this->assign('kw_reply_info',$kw_reply_info);
        return $this->fetch();
    }

    public function update($id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $save_data = [
                'name' => $data['name'],
                'mode' => $data['mode'],
            ];

            foreach($data['match'] as $k=>$v){
                $save_data['keyword_list_info'][] = [
                    'match_mode' => $v,
                    'content' => $data['keyword'][$k],
                ];
            }

            foreach($data['type'] as $k2=>$v2){
                $save_data['reply_list_info'][] = [
                    'type' => $v2,
                    'content' => $data['content'][$k2],
                ];
            }

            $result = $this->kw_reply_model->allowField(true)->save($save_data,['id' => $id]);
            if($result){
                return $this->success('修改成功','admin/kw_reply/index');
            }else{
                return $this->success('修改失败');
            }
        }
    }

    public function delete($id){
        $result = $this->kw_reply_model->destroy($id);
        if($result){
            $this->success('删除成功');
        }else{
            $this->success('删除失败');
        }
    }
}